package com.nowcoder.Offer.List;

import org.junit.Test;

/**
 * 找到链表倒数第K个节点
 */
public class FindLastKNode {

    public ListNode FindKthToTail(ListNode head,int k) {
        if(head == null) return head;
        ListNode kNode = head, tailNode = head;
        while(k--!=0){
            tailNode = tailNode.next;
            if(tailNode == null && k != 0){
                return null;
            }
        }



        while(tailNode!=null){
            tailNode = tailNode.next;
            kNode = kNode.next;
        }

        return kNode;
    }

    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;

        ListNode res = FindKthToTail(node1,3);

        System.out.println(res.val);
    }
}
